package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> querySpecGroupByCategoryId(Long id) {

        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(query().eq("category_id", id).list());

        if (CollectionUtils.isEmpty(groupList)) {
            throw new LyException(404, "该规格组不存在!");
        }

        List<SpecParamDTO> paramDTOList = paramService.querySpecParam(id, null, null);

        Map<Long, List<SpecParamDTO>> map = paramDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        for (SpecGroupDTO specGroupDTO : groupList) {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }

        return groupList;
    }
}